package tools

import (
	"fmt"
	"github.com/streadway/amqp"
	"time"
)

type RabbitMqHelper struct {
	MQConn           *amqp.Connection
	MQChannel        *amqp.Channel
	MQInitStatus     bool
	NQInitTime       time.Time
	ConnectionString string
	Exchange         string
	ExchangeType     string
	DeliveryMode     uint8
}

func (this *RabbitMqHelper) InitMQConnection() {
	if this.MQConn == nil || this.MQChannel == nil || !this.MQInitStatus {
		var err error
		this.MQConn, err = amqp.Dial(this.ConnectionString)
		if err != nil {
			//MQ拨号异常
			fmt.Println("ConnectMQ:dial to rabbitmq error:" + this.ConnectionString + "|" + err.Error())
			this.NQInitTime = time.Now()
			return
		}
		this.MQChannel, err = this.MQConn.Channel()
		if err != nil {
			fmt.Println("ConnectMQ:create channel error:" + err.Error())
			this.NQInitTime = time.Now()
			return
		}
		if err := this.MQChannel.ExchangeDeclare(
			this.Exchange,     // name
			this.ExchangeType, // type
			false,             // durable
			true,              // auto-deleted
			false,             // internal
			false,             // noWait
			nil,               // arguments
		); err != nil {
			fmt.Println("ConnectMQ:declare exchange error:" + this.Exchange + "," + this.ExchangeType + "|" + err.Error())
			this.NQInitTime = time.Now()
			return
		}
		this.MQInitStatus = true
		this.NQInitTime = time.Now()
	}
}

//region 发送MQ消息
func (this *RabbitMqHelper) SendMQMessageWithRoutekey(msginfo []byte, routekey string) bool {
	err := this.MQChannel.Publish(
		this.Exchange, // exchange
		routekey,      // routing key
		false,         // mandatory
		false,         // immediate
		amqp.Publishing{
			DeliveryMode: this.DeliveryMode,
			Body:         msginfo,
		})
	if err != nil {
		//发送消息失败
		fmt.Println("ConnectMQ:publish message error:" + this.Exchange + "," + this.ExchangeType + "," + string(msginfo) + "|" + err.Error())
		if time.Now().Sub(this.NQInitTime).Minutes() > 1 {
			this.MQInitStatus = false
		}
		return false
	}
	return true
}

//endregion
